package messages

import (
	"fmt"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	dysmsapiClient "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
)

// AliCloudCodeSMS 阿里云-验证码短信发送
type AliCloudCodeSMS struct {
	access configstc.ThirdConfig

	region       string
	endPoint     string
	templateCode string //短信模板code
	signName     string //签名

	client *dysmsapiClient.Client
}

func NewAliCloudCodeSMS(conf configstc.ThirdConfig) *AliCloudCodeSMS {
	s := &AliCloudCodeSMS{
		access: conf,

		region:       conf.ExtendParams.ExtendParamValue("Region", "cn-hangzhou"),
		endPoint:     conf.ExtendParams.ExtendParamValue("EndPoint", "dysmsapi.aliyuncs.com"),
		templateCode: conf.ExtendParams.ExtendParamValue("TemplateCode", ""),
		signName:     conf.ExtendParams.ExtendParamValue("SignName", ""),
	}
	s.initClient()
	return s
}

func (s *AliCloudCodeSMS) Allow(target string) bool {
	return true
}

func (s *AliCloudCodeSMS) initClient() {
	config := new(openapi.Config)
	// 使用 ak 初始化 config
	config.SetAccessKeyId(s.access.AppKey).
		SetAccessKeySecret(s.access.AppSecret).
		SetRegionId(s.region).
		SetEndpoint(s.endPoint)
	client, err := dysmsapiClient.NewClient(config)
	common.ErrPanic(err)
	s.client = client
}

// Send 发送,msg为验证码
func (s *AliCloudCodeSMS) Send(target string, msg string) error {
	if target == "" {
		return fmt.Errorf("target invalid")
	}
	if s.templateCode == "" {
		return fmt.Errorf("sms template code empty")
	}
	if s.signName == "" {
		return fmt.Errorf("sms sign empty")
	}
	// 初始化 runtimeObject
	runtimeObject := new(util.RuntimeOptions).SetAutoretry(false).SetMaxIdleConns(3)
	//
	req := new(dysmsapiClient.SendSmsRequest)
	req.SetTemplateCode(s.templateCode)
	req.SetSignName(s.signName)
	req.SetTemplateParam(fmt.Sprintf("{\"code\":\"%s\"}", msg))
	req.SetPhoneNumbers(target)
	//发送
	_, err := s.client.SendSmsWithOptions(req, runtimeObject)
	if err != nil {
		return err
	}
	return nil
}
